package com.wicture.erp4android.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.wicture.erp4android.R;

/**
 * 登录页面
 * @author Administrator
 *
 */
public class LoginAct extends Activity implements OnClickListener{
	private EditText et_username;
	private EditText et_password;
	private Button btn_login;
	private Button btn_equit;

	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_login);
		et_username = (EditText) findViewById(R.id.et_username);
		et_password = (EditText) findViewById(R.id.et_password);
		btn_login = (Button) findViewById(R.id.btn_login);
		btn_equit = (Button) findViewById(R.id.btn_equit);
		btn_login.setOnClickListener(this);
		btn_equit.setOnClickListener(this);
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_login:
			
			login(et_username.getText().toString(),et_password.getText().toString());
			toMainAct();
			break;
		case R.id.btn_equit:
			Toast.makeText(getApplicationContext(), "注销", Toast.LENGTH_SHORT).show();
			break;
		default:
			break;
		}
		
	}

	private void login(final String userName, final String password){
		HttpUtils http = new HttpUtils(5000);
		http.send(HttpMethod.GET, "http://www.126.com", new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException e, String arg1) {
				Toast.makeText(getApplicationContext(), "服务器无响应", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
				//保存账号密码
				SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
				Editor edit = sp.edit();
				edit.putString("user", userName);
				edit.putString("password", password);
				edit.commit();
			}

			@Override
			public void onLoading(long total, long current, boolean isUploading) {
				// TODO Auto-generated method stub
				super.onLoading(total, current, isUploading);
			}
			
		});
		
	}
	
/**
 * 跳转到主界面
 */
	private void toMainAct(){
		Intent intent = new Intent(this,MainAct.class);
		startActivity(intent);
		finish();
		
	}

}
